package com.caigou.modules.article.ui.fragment

import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.GridLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.caigou.comm.base.bus.BusKey
import com.caigou.comm.base.bus.LiveDataBus
import com.caigou.comm.base.constants.AppConstants
import com.caigou.comm.base.constants.RouterPath
import com.caigou.comm.base.container.BaseFragment
import com.caigou.comm.base.ext.Resource
import com.caigou.comm.base.ext.observe
import com.caigou.comm.base.ext.showToast
import com.caigou.comm.base.viewmodel.ReportViewModel
import com.caigou.comm.base.widget.SpaceItemDecoration
import com.caigou.modules.article.adpter.ArticleItemAdapter
import com.caigou.modules.article.bean.ArticleBean
import com.caigou.modules.article.databinding.FragmentMoreArticleBinding
import com.caigou.modules.article.ui.ArticleActivity
import com.caigou.modules.article.viewmodel.ArticleViewModel
import dagger.hilt.android.AndroidEntryPoint

/**
 * @author #Suyghur.
 * Created on 2021/11/25
 */
@AndroidEntryPoint
class MoreArticleFragment : BaseFragment() {

    private var _binding: FragmentMoreArticleBinding? = null
    private val binding get() = _binding!!

    private val articleViewModel: ArticleViewModel by viewModels()

    private var page = 1
    private val limit = 10
    private var totalPage = 0

    private val mAdapter: ArticleItemAdapter by lazy {
        ArticleItemAdapter(mutableListOf())
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        _binding = FragmentMoreArticleBinding.inflate(inflater, container, false)
        return _binding?.root
    }

    override fun initView() {

        mAdapter.loadMoreModule.run {
            setOnLoadMoreListener {
                mAdapter.loadMoreModule.isEnableLoadMore = true
                fetchMoreArticleList()
            }
            isAutoLoadMore = true
            isEnableLoadMoreIfNotFullPage = false
        }

        binding.moreArticleRecyclerView.run {
            layoutManager = GridLayoutManager(requireActivity(), 2)
            adapter = mAdapter
            itemAnimator = DefaultItemAnimator()
            addItemDecoration(SpaceItemDecoration(requireActivity()))
        }

        mAdapter.setOnItemClickListener { adapter, view, position ->
            val bean = mAdapter.getItem(position)
            ARouter.getInstance().build(RouterPath.Article.PAGE_ARTICLE)
                .withObject(AppConstants.ARTICLE_ITEM_BEAN, bean)
                .withInt(AppConstants.DATA_ID, bean.dataId)
                .navigation()
        }
    }

    override fun lazyLoad() {
        fetchMoreArticleList()
    }

    override fun onBack() {
    }

    override fun onResume() {
        super.onResume()
        binding.root.requestLayout()
    }

    override fun observeViewModel() {
        observe(articleViewModel.moreArticleListLiveData, ::handleGetMoreArticleList)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    private fun handleGetMoreArticleList(result: Resource<ArticleBean>) {
        when (result) {
            is Resource.Loading -> {
            }
            is Resource.DataError -> {
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("获取资料信息异常")
                }
            }
            is Resource.Success -> {
                if (result.data == null) {
                    binding.moreArticleLlEmpty.visibility = View.VISIBLE
                    binding.moreArticleRecyclerView.visibility = View.GONE
                    return
                }

                if (result.data!!.list.isNullOrEmpty()) {
                    binding.moreArticleLlEmpty.visibility = View.VISIBLE
                    binding.moreArticleRecyclerView.visibility = View.GONE
                } else {
                    binding.moreArticleLlEmpty.visibility = View.GONE
                    binding.moreArticleRecyclerView.visibility = View.VISIBLE
                }

                totalPage = result.data!!.totalPage

                if (page == 1) {
                    mAdapter.setList(result.data!!.list)
                } else {
                    mAdapter.addData(result.data!!.list)
                }

                if (result.data!!.pageSize < limit) {
                    mAdapter.loadMoreModule.loadMoreEnd(false)
                } else {
                    mAdapter.loadMoreModule.loadMoreComplete()
                }

                if (page >= totalPage) {
                    mAdapter.loadMoreModule.loadMoreEnd(false)
                } else {
                    page++
                }
                LiveDataBus.get().with(BusKey.LOAD_VP2_FINISH).value = Any()
            }
        }
    }

    fun fetchMoreArticleList() {
        articleViewModel.getMoreArticleList(page, limit, (requireActivity() as ArticleActivity).articleItemBean.userInfo.userId)
    }
}